import { createI18n } from "vue-i18n"
import { getStore } from "@/utils/store.js"
declare type EmptyObjectType<T = any> = {
	[key: string]: T;
}

// element plus 自带国际化
import enLocale from 'element-plus/es/locale/lang/en';
import zhcnLocale from 'element-plus/es/locale/lang/zh-cn';
import zhtwLocale from 'element-plus/es/locale/lang/zh-tw';

const messages = {}
const element = { 'en': enLocale, 'zh-CN': zhcnLocale, 'zh-TW': zhtwLocale };
const itemize = { 'en': [], 'zh-CN': [], 'zh-TW': [] };
const modules: Record<string, any> = import.meta.glob("./*.ts",{ eager: true });
for (const path in modules) {
	const key = path.match(/(\S+)\/(\S+).ts/);
    if(key!='index'){
        if (itemize[key![2]]) itemize[key![2]].push(modules[path].default);
        else itemize[key![2]] = modules[path];
    }
}
// 合并数组对象（非标准数组对象，数组中对象的每项 key、value 都不同）
function mergeArrObj<T>(list: T, key: string) {
	let obj = {};
	list[key].forEach((i: EmptyObjectType) => {
		obj = Object.assign({}, obj, i);
	});
	return obj;
}

// 处理最终格式
for (const key in itemize) {
	// console.log(itemize)
	// console.log(key)
	messages[key] = {
		name: key,
		el: element[key].el,
		message: mergeArrObj(itemize, key),
	};
}
let lang = getStore({name:'lang'})
if(!lang){
	const navigator = window.navigator
	lang = navigator.language || 'zh-CN'
}
const i18n = createI18n({
    legacy: false,
    locale: lang, // set default locale
    fallbackLocale:lang, // set fallback locale
    globalInjection:true,//全局配置$t
    allowcomposition : true, // 允许組合式api
    messages
})

export default i18n